import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd';
import { retry } from 'rxjs/operators';

declare var form: any;
declare var base: any;
declare var security: any;

@Component({
  templateUrl: './syn.manage.html'
})
export class SynManageComponent {
  fs: any = null;
  proDic: any = null;
  stateDic: any = null;
  constructor(
    private http: HttpClient,
    private msg: NzMessageService) {

    this.fs = new form.FormSideTreeService('datalock', {
      keyField: 'guid',
      orderObject: { order: 0 },
      pageSize: 1000,
      foreignKey: 'projectid'
    });

    // 初始化字典
    this.proDic = new form.DictionaryService('p_style_directory');
    this.proDic.load('0');
    this.stateDic = new form.DictionaryService('g_datalock_state');
  }

  initlock() {
    const fo = this.fs;
    if (!fo.foreignValue) {
      return;
    }

    const url = base.BaseService.getHostUrl() + '/datalock/init/' + fo.foreignValue;
    const jwts = security.SecurityService.jwt;
    const obsData = this.http.post<boolean>(url, null, { headers: new HttpHeaders({ jwt: jwts }) })
      .pipe(retry(1));
    obsData.subscribe(
      (data) => {
        fo.isLoading = false;
        if (data) {
          this.fs.loadData('datalock');
        } else {
          this.msg.error('初始化失败，请确认锁定数据为空，以及能访问到政区数据!');
        }
      },
      (error) => {
        fo.isLoading = false;
        this.msg.error('初始化失败，请确认锁定数据为空，以及能访问到政区数据!');
      }
    );
  }

  unLock(row) {
    const fo = this.fs;
    if (!fo.foreignValue) {
      return;
    }
    if (!row) {
      return;
    }

    const url = base.BaseService.getHostUrl() + '/datalock/unLock/' + row.guid;
    const jwts = security.SecurityService.jwt;
    const obsData = this.http.post<void>(url, null, { headers: new HttpHeaders({ jwt: jwts }) })
      .pipe(retry(1));

    obsData.subscribe(
      () => {
        fo.isLoading = false;
        row.lockState = '1';
        row.lockStateName = '未锁定';
        row.lockUserID = '';
        row.lockUserName = '';
        row.lockEquipmentID = '';
      },
      (error) => {
        fo.isLoading = false;
        this.msg.error('解锁失败!');
      }
    );
  }
}
